package com.example.edianzu.somur.utils.view;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.edianzu.somur.R;
import com.example.edianzu.somur.utils.manager.ActivityManager;
import com.example.edianzu.somur.utils.service.CustomCaller;
import com.example.edianzu.somur.utils.service.CustomService;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

public class BaseActivity extends RxAppCompatActivity implements BaseView, SwipeRefreshLayout.OnRefreshListener, ContentFragment.NavigationIconOnClickListener {

//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
//        setContentView(R.layout.activity_base);
//
//        ActivityManager.addActivity(this);
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//
//        ActivityManager.removeActivity(this);
//    }

    private Toolbar toolbar;
    private LinearLayout contentView;
    public boolean isEnableBackArrow = false;
    private Fragment preFragment;
    private Dialog dialog;
    private CustomCaller customCaller;
    private CriFMServiceConnection criFMServiceConnection;
    public int width, height;
    private TextView title;
    private Dialog shareDialog;
    public RecyclerView recyclerView;
    public int layoutId;
    public int customerLayoutId = 0;
    private CoordinatorLayout rootView;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private static BaseActivity baseActivity;

    public static Context getAppContext() {
        return baseActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //hideStatusBar(false);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
//判断版本,如果[4.4,5.0)就设置状态栏和导航栏为透明
        if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT
                &&android.os.Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.LOLLIPOP){
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //设置虚拟导航栏为透明
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        ActivityManager.addActivity(this);
        showLoadView();
        //设置activity的进出场动画
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
//        if (layoutId == R.layout.content_view_base) {//activity嵌套fragment模版
//            setContentView(layoutId);
//            initBaseView();
//            loadCustomerLayout();
//        } else if (layoutId == R.layout.content_view_recycler_view) {//activity+recyclerView的模版
//            setContentView(layoutId);
//            initRecyclerView();//初始化RecyclerView
//            initSwipeRefreshLayout();
//        } else if (layoutId == R.layout.content_view_behavior) {//toolbar可折叠模版
//            setContentView(layoutId);
//            initRecyclerView();
//            initBehaviorView();
//        } else {//用户自定义模版
//            setContentView(layoutId);
//            return;
//        }

//        initCommonView();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获取屏幕宽
        width = dm.widthPixels;
        //获取屏幕高
        height = dm.heightPixels;
    }

    @SuppressLint("NewApi")
    public void setOrChangeTranslucentColor(Toolbar toolbar,View bottomNavigationBar, int translucentPrimaryColor){
        //判断版本,如果[4.4,5.0)就设置状态栏和导航栏为透明
        if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT
                &&android.os.Build.VERSION.SDK_INT<android.os.Build.VERSION_CODES.LOLLIPOP){
            if(toolbar!=null){
                //1.先设置toolbar的高度
                ViewGroup.LayoutParams params = toolbar.getLayoutParams();
                int statusBarHeight = getStatusBarHeight(this);
                params.height += statusBarHeight ;
                toolbar.setLayoutParams(params );
                //2.设置paddingTop，以达到状态栏不遮挡toolbar的内容。
                toolbar.setPadding(
                        toolbar.getPaddingLeft(),
                        toolbar.getPaddingTop()+getStatusBarHeight(this),
                        toolbar.getPaddingRight(),
                        toolbar.getPaddingBottom());
                //设置顶部的颜色
                toolbar.setBackgroundColor(translucentPrimaryColor);
            }
            if(bottomNavigationBar!=null){
                //解决低版本4.4+的虚拟导航栏的
                if(hasNavigationBarShow(getWindowManager())){
                    ViewGroup.LayoutParams p = bottomNavigationBar.getLayoutParams();
                    p.height += getNavigationBarHeight(this);
                    bottomNavigationBar.setLayoutParams(p);
                    //设置底部导航栏的颜色
                    bottomNavigationBar.setBackgroundColor(translucentPrimaryColor);
                }
            }
        }else if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.LOLLIPOP){
            getWindow().setNavigationBarColor(translucentPrimaryColor);
            getWindow().setStatusBarColor(translucentPrimaryColor);
        }else{
            //<4.4的，不做处理
        }
    }

    private int getNavigationBarHeight(Context context) {
        return getSystemComponentDimen(this, "navigation_bar_height");
    }

    /**
     * 获取状态栏的高度
     * @param context
     * @return
     */
    private int getStatusBarHeight(Context context) {
        // 反射手机运行的类：android.R.dimen.status_bar_height.
        return getSystemComponentDimen(this, "status_bar_height");
    }

    private static int getSystemComponentDimen(Context context, String dimenName){
        // 反射手机运行的类：android.R.dimen.status_bar_height.
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            String heightStr = clazz.getField(dimenName).get(object).toString();
            int height = Integer.parseInt(heightStr);
            //dp--->px
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    private static boolean hasNavigationBarShow(WindowManager wm){
        Display display = wm.getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        //获取整个屏幕的高度
        display.getRealMetrics(outMetrics);
        int heightPixels = outMetrics.heightPixels;
        int widthPixels = outMetrics.widthPixels;
        //获取内容展示部分的高度
        outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);
        int heightPixels2 = outMetrics.heightPixels;
        int widthPixels2 = outMetrics.widthPixels;
        int w = widthPixels-widthPixels2;
        int h = heightPixels-heightPixels2;
        System.out.println("~~~~~~~~~~~~~~~~h:"+h);
        return  w>0||h>0;//竖屏和横屏两种情况。
    }

    /**
     * 隐藏状态栏
     *
     * @param enable
     */
    private void hideStatusBar(boolean enable) {
        WindowManager.LayoutParams p = this.getWindow().getAttributes();
        if (enable) {

            p.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;//|=：或等于，取其一

        } else {
            p.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);//&=：与等于，取其二同时满足,~ ： 取反

        }
        getWindow().setAttributes(p);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

    }

    @Override
    protected void onResume() {
        super.onResume();
        hindLoadView();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 显示加载视图
     */
    @Override
    public void showLoadView() {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.Translucent_Dialog);
        }
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setContentView(R.layout.content_load_view);//设置view
        Window w = dialog.getWindow();//获取窗口
        w.setGravity(Gravity.BOTTOM);//Dialog的位置
        w.setWindowAnimations(R.style.Bottom_Dialog_Anim);
        w.getDecorView().setPadding(0, 0, 0, 0);//对话框充满屏幕
        w.setLayout(width, height);//设置大小

    }

    /**
     * 隐藏加载视图
     */
    @Override
    public void hindLoadView() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 初始化动态加载加载子视图容器contentView
     * 初始化toolbar
     * 初始化居中标题 TextView
     * 设置toolbar带title使其不显示App默认标题
     */
    @Override
    public void initCommonView() {
        rootView = (CoordinatorLayout) findViewById(R.id.root_view);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        title = (TextView) findViewById(R.id.title);
        toolbar.setTitle("");
        toolbar.setNavigationIcon(R.drawable.ic_arrow);
        setSupportActionBar(toolbar);
        setToolbarBackArrowEnable(isEnableBackArrow);
    }

    @Override
    public void initBaseView() {
        contentView = (LinearLayout) findViewById(R.id.content_view);
    }

    @Override
    public void initBehaviorView() {
        collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
    }

    @Override
    public void initSwipeRefreshLayout() {
        SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) findViewById(R.id.cri_refresh);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(ContextCompat.getColor(this, R.color.dodgerBlue)
                , ContextCompat.getColor(this, R.color.red)
                , ContextCompat.getColor(this, R.color.deepSkyBlue)
                , ContextCompat.getColor(this, R.color.dodgerBlue));
    }

    /**
     * 初始化RecyclerView
     */
    @Override
    public void initRecyclerView() {
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    /**
     * 初始化RecyclerView的滑动监听
     */
    @Override
    public void initRecyclerViewScrollListener() {
        recyclerView = (RecyclerView) findViewById(R.id.rv);
        recyclerView.addOnScrollListener(onScrollListener);
    }

    private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
            int position = manager.findLastCompletelyVisibleItemPosition();
            if (position + 1 == recyclerView.getAdapter().getItemCount()) {
                if (onLoadMoreListener != null) {
                    onLoadMoreListener.onLode();
                }
            }
        }
    };

    @Override
    public void goBackListener() {

    }

    @Override
    public void onRefresh() {

    }

    public interface OnLoadMoreListener {
        void onLode();
    }

    private OnLoadMoreListener onLoadMoreListener;

    public void setLoadMoreListener(OnLoadMoreListener loadMoreListener) {
        this.onLoadMoreListener = loadMoreListener;
    }

    /**
     * 设置返回键
     */
    @Override
    public void setToolbarBackArrowEnable(boolean isEnable) {
        if (isEnable) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

    }

    /**
     * toolbar返回箭头的监听
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 设置居中标题
     *
     * @param middleTitle
     */
    @Override
    public void setMiddleTitle(String middleTitle) {
        title.setVisibility(View.VISIBLE);
        title.setText(middleTitle);
    }

    /**
     * 设置导航栏Icon
     *
     * @param resId
     */
    @Override
    public void setToolbarNavigationIcon(int resId) {
        toolbar.setNavigationIcon(resId);
    }

    /**
     * 设置导航栏点击事件
     *
     * @param onClickListener
     */
    @Override
    public void setToolbarNavigationListener(@NonNull View.OnClickListener onClickListener) {
        toolbar.setNavigationOnClickListener(onClickListener);
    }

    /**
     * 设置logo
     *
     * @param resId
     */
    @Override
    public void setToolbarLogo(int resId) {
        toolbar.setLogo(resId);
    }


    /**
     * 加载自定义视图
     *
     * @param
     */
    @Override
    public void loadCustomerLayout() {
        if (customerLayoutId != 0) {
            View view = View.inflate(this, customerLayoutId, null);
            contentView.addView(view, 0, new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT));
        }


    }

    /**
     * 加载折叠视图
     *
     * @param layoutId
     */
    @Override
    public void loadBehaviorView(int layoutId) {
        collapsingToolbarLayout.addView(View.inflate(this, layoutId, null), 0, new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT));
    }

    /**
     * snackBar提示信息
     *
     * @param message
     */
    @Override
    public void setHintMessage(String message) {
        Snackbar snackbar = Snackbar.make(rootView, "温馨提示^_^\t\t" + message, Snackbar.LENGTH_LONG);
        View view = snackbar.getView();
        view.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
        TextView textView = (TextView) view.findViewById(R.id.snackbar_text);
        textView.setTextColor(ContextCompat.getColor(this, R.color.white));
        snackbar.show();


    }


    /**
     * @param hint
     * @param message
     * @param onClickListener 点击监听
     */
    @Override
    public void setHintMessage(String hint, String message, @NonNull View.OnClickListener onClickListener) {
        Snackbar snackbar = Snackbar.make(rootView, "温馨提示^_^\t\t" + message, Snackbar.LENGTH_LONG);
        View view = snackbar.getView();
        view.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
        TextView textView = (TextView) view.findViewById(R.id.snackbar_text);
        textView.setTextColor(ContextCompat.getColor(this, R.color.yellow));
        snackbar.setAction(hint, onClickListener).show();
    }

    /**
     * 自定义Dialog
     *
     * @param layoutId
     */
    @Override
    public void setCustomerDialog(@LayoutRes int layoutId) {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.Translucent_Dialog);
        }
        dialog.show();
        dialog.setContentView(layoutId);//设置view
        Window w = dialog.getWindow();//获取窗口
        w.setGravity(Gravity.TOP);//Dialog的位置
        w.setWindowAnimations(R.style.Bottom_Dialog_Anim);
        w.getDecorView().setPadding(0, 0, 0, 0);//对话框充满屏幕
        w.setLayout(width, height / 5);//设置大小
    }

    /**
     * 自定义Dialog
     *
     * @param layoutId
     */

    public Window setCustomerDialog(@LayoutRes int layoutId, int gravity, int style, int animStyle, int width, int height) {

        Dialog dialog = new Dialog(this, style);
        dialog.show();
        dialog.setContentView(layoutId);//设置view
        Window w = dialog.getWindow();//获取窗口
        w.setGravity(gravity);//Dialog的位置
        w.setWindowAnimations(animStyle);
        w.getDecorView().setPadding(0, 0, 0, 0);//对话框充满屏幕
        w.setLayout(width, height);//设置大小
        return w;
    }

    /**
     * 底部dialog
     *
     * @param layoutId
     * @param itemId
     * @param onClickListener
     */
    @Override
    public void setBottomDialog(@LayoutRes int layoutId, @IdRes int[] itemId, @NonNull View.OnClickListener onClickListener) {
        if (dialog == null) {
            dialog = new Dialog(this, R.style.Translucent_Dialog);
        }
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setContentView(layoutId);//设置view
        Window w = dialog.getWindow();//获取窗口
        w.setGravity(Gravity.BOTTOM);//Dialog的位置
        w.setWindowAnimations(R.style.Bottom_Dialog_Anim);
        w.getDecorView().setPadding(0, 0, 0, 0);//对话框充满屏幕
        w.setLayout(getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight() - 100);//设置大小
        for (int i = 0; i < itemId.length; i++) {
            w.findViewById(itemId[i]).setOnClickListener(onClickListener);
        }
    }

    /**
     * 取消底部dialog
     */
    @Override
    public void cancelBottomDialog() {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

    }


//    /**
//     * 分享对话框
//     */
//    public void setShareDialog(final Intent intent) {
//
//        if (shareDialog == null) {
//            shareDialog = new Dialog(this, R.style.Translucent_Dialog);
//        }
//        shareDialog.show();
//        shareDialog.setContentView(R.layout.dialog_share);
//        Window window = shareDialog.getWindow();
//        window.setGravity(Gravity.BOTTOM);//Dialog的位置
//        window.setWindowAnimations(R.style.Bottom_Dialog_Anim);
//        window.getDecorView().setPadding(0, 0, 0, 0);//对话框充满屏幕
//        window.setLayout(width, height / 2);//设置大小
//        window.findViewById(R.id.share_facebook).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                L.e("facebook");
//                IntentUtil.startActivityForResultNetWork(intent, SHARE_REQUEST_CODE);
//            }
//        });
//        window.findViewById(R.id.share_twitter).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                IntentUtil.startActivityForResultNetWork(intent, SHARE_REQUEST_CODE);
//            }
//        });
//
//    }

    /**
     * @param target      要切换的目标Fragment
     * @param layoutId    替换布局ID
     * @param fragmentTag Fragment的标签
     */
    public void changeFragment(Fragment target, int layoutId, String fragmentTag) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_right);
        if (preFragment != null) {
            if (preFragment != target) {
                if (!target.isAdded()) { // 先判断是否被add过
                    // 隐藏当前的fragment，add下一个到Activity中
                    transaction.hide(preFragment).add(layoutId, target, fragmentTag);
                } else {
                    transaction.hide(preFragment).show(target); // 隐藏当前的fragment，显示下一个
                }
            }
        } else {
            transaction.add(layoutId, target, fragmentTag);
        }
        /**
         * Can not perform this action after onSaveInstanceState
         * onSaveInstanceState方法是在该Activity即将被销毁前调用，来保存Activity数据的，如果在保存玩状态后
         * 再给它添加Fragment就会出错。解决办法就是把commit（）方法替换成 commitAllowingStateLoss()就行了，其效果是一样的。
         */
        transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();  //推荐使用此方法，更安全，更方便
        preFragment = target;
    }


    /**
     * 连接服务类
     */
    private class CriFMServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            customCaller = (CustomCaller) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public CustomCaller getCriFMCaller() {
        return customCaller;
    }

    /**
     * 绑定服务类
     */
    @Override
    protected void onStart() {
        super.onStart();
        if (criFMServiceConnection == null) {
            criFMServiceConnection = new CriFMServiceConnection();
        }

        Intent intent = new Intent(this, CustomService.class);
        bindService(intent, criFMServiceConnection, BIND_AUTO_CREATE);
    }

    /**
     * 销毁服务类
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();

        ActivityManager.removeActivity(this);
        if (criFMServiceConnection != null) {
            unbindService(criFMServiceConnection);
            criFMServiceConnection = null;
        }

    }

    /**
     * activity退出动画
     */
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
}
